package com.spn.blog.login.privider;

import com.alibaba.fastjson.JSON;
import com.spn.blog.common.dao.pojo.SysUser;
import com.spn.blog.login.params.PrividerToken;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class AccessPrivider {
    public String getToken(PrividerToken prividerToken) {
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();

        // 创建一个Post请求，带着gitee的访问码去获取token
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(prividerToken));
        Request request = new Request.Builder()
                .url("https://gitee.com/oauth/token?grant_type=authorization_code&code=" + prividerToken.getCode()
                        + "&client_id=" + prividerToken.getClient_id()
                        + "&redirect_uri=" + prividerToken.getRedirect_uri()
                        + "&client_secret=" + prividerToken.getClient_Secret())
                .post(body)
                .build();


        try (Response response = client.newCall(request).execute()) {

            String string = response.body().string();
            //{
            // "access_token":"d3c84e51d324935bd9d8cb86d37cc642",
            // "token_type":"bearer","expires_in":86400,
            // "refresh_token":"7075878fdae132ceb1275cf5b20cff2324d0407e1fd0d51b3c5467784aae6f7d",
            // "scope":"user_info",
            // "created_at":1653799245
            // }

            String str1 = string.split(":")[1];
            String token = str1.split("\"")[1];

            System.out.println("token:    " + token);
            return token;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public SysUser getSysUser(String Token) {
        OkHttpClient client = new OkHttpClient();

        // 发起一个get请求，附带token去获取用户信息
        Request request = new Request.Builder()
                .url("https://gitee.com/api/v5/user?access_token=" + Token)
                .build();

        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            //{
            // "id":10850007,
            // "name":"SPN",
            // "avatar_url":"https://portrait.gitee.com/uploads/avatars/user/3616/10850007_SuPerNaturalBT_1650962398.png",
            // "email":null
            // }
            String str1 = string.split(":")[2];
            String nickname = str1.split("\"")[1];
            SysUser sysUser = JSON.parseObject(string, SysUser.class);
            sysUser.setNickname(nickname);
            return sysUser;
        } catch (IOException e) {

        }
        return null;
    }
}
